#!/usr/bin/env python
# stoker_do: Implementation of Stoker "do" command
#
# Author:   Mike Murphy (mamurph@cs.clemson.edu)
# Revision: 26 February 2009
#
#   Copyright 2007-2009 Clemson University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
# This material is based upon work supported under a National Science
# Foundation Graduate Research Fellowship. Any opinions, findings,
# conclusions or recommendations expressed in this publication are those of
# the author(s) and do not necessarily reflect the views of the National
# Science Foundation.

import stoker_base
from stoker_defines import HOSTNAME_KEY, IPV4_KEY, MAC_KEY

class DoCommand(stoker_base.CommandObjectBase):
   def __init__(self, stoker_config, opts, args, target, extra):
      stoker_base.CommandObjectBase.__init__(self, stoker_config, opts, args, \
                                             target, extra)
      self.hostname = ''
      self.ipv4 = ''
      self.mac = ''
      if HOSTNAME_KEY in self.extra:
         self.hostname = self.extra[HOSTNAME_KEY]
      if IPV4_KEY in self.extra:
         self.ipv4 = self.extra[IPV4_KEY]
      if MAC_KEY in self.extra:
         self.mac = self.extra[MAC_KEY]
      #
      self.command = self.args[0].strip()
      arglist = []
      for arg in self.args[1:]:
         raw_arg = arg.strip()
         raw_arg = raw_arg.replace('%target.hostname', self.hostname)
         raw_arg = raw_arg.replace('%target.ipv4', self.ipv4)
         raw_arg = raw_arg.replace('%target.mac', self.mac)
         raw_arg = raw_arg.replace('%target', self.target)
         arglist.append(raw_arg)
      self.args = arglist
   #
   def execute(self, stdin=''):
      # Run the local command
      return stoker_base.run_external(self.command, self.args, stdin)
   #
